home *** CD-ROM | disk | FTP | other *** search
- LISTING 9 - A card shuffling program that illustrates the random number and
- integer division functions in <stdlib.h>
-
- /* deal.c: Deal a hand from a shuffled deck of cards */
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <time.h>
-
- #define DECKSIZE 52
- #define SUITSIZE 13
-
- main(int argc, char *argv[])
- {
- int ncards = DECKSIZE; /* Deal full deck by default */
- char deck[DECKSIZE]; /* An array of small integers */
- size_t deckp;
- unsigned int seed;
-
- /* Get optional hand size */
- if (argc > 1)
- if ((ncards = abs(atoi(argv[1])) % DECKSIZE) == 0)
- ncards = DECKSIZE;
-
- /* Seed the random number generator */
- seed = (unsigned int) time(NULL);
- srand(seed);
-
- /* Shuffle */
- deckp = 0;
- while (deckp < ncards)
- {
- int num = rand() % DECKSIZE;
- if (memchr(deck, num, deckp) == NULL)
- deck[deckp++] = (char) num;
- }
-
- /* Deal */
- for (deckp = 0; deckp < ncards; ++deckp)
- {
- div_t card = div(deck[deckp], SUITSIZE);
- printf(
- "%c(%c)%c",
- "A23456789TJQK"[card.rem],
- "CDHS"[card.quot],
- (deckp+1) % SUITSIZE ? ' ' : '\n'
- );
- }
-
- return 0;
- }
-
- /* Output: */
- A(C) 6(S) 7(C) 9(C) 3(H) 6(C) 8(D) 3(C) 6(D) 5(D) 2(H) A(S) 4(H)
- 8(C) 8(H) 6(H) J(S) 7(S) Q(C) 2(C) Q(H) K(H) 4(C) 5(S) T(H) Q(S)
- 9(H) T(D) T(S) 9(D) K(C) 3(S) J(C) 5(C) T(C) K(S) 7(D) 2(D) 4(S)
- 8(S) 5(H) A(D) 7(H) 3(D) Q(D) A(H) 2(S) J(D) 9(S) K(D) J(H) 4(D)
-
-